import json
import os
from django.core.management.base import BaseCommand
from navigation.models import NavigationGroup, NavigationLink

class Command(BaseCommand):
    help = '从 nav_data.json 文件导入导航数据'

    def handle(self, *args, **kwargs):
        try:
            # 获取 nav_data.json 文件的路径
            json_file = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))), 'nav_data.json')
            
            # 读取 JSON 文件
            with open(json_file, 'r', encoding='utf-8') as f:
                data = json.load(f)
            
            # 遍历并创建导航组和链接
            for group_data in data.get('groups', []):
                # 创建或更新导航组
                group, created = NavigationGroup.objects.get_or_create(
                    title=group_data['title'],
                    defaults={'order': group_data.get('order', 0)}
                )
                
                if not created:
                    group.order = group_data.get('order', 0)
                    group.save()
                
                # 遍历并创建该组下的链接
                for link_data in group_data.get('links', []):
                    link, created = NavigationLink.objects.get_or_create(
                        name=link_data['name'],
                        group=group,
                        defaults={
                            'url': link_data['url'],
                            'icon': link_data.get('icon', 'fas fa-link'),
                            'order': link_data.get('order', 0)
                        }
                    )
                    
                    if not created:
                        link.url = link_data['url']
                        link.icon = link_data.get('icon', 'fas fa-link')
                        link.order = link_data.get('order', 0)
                        link.save()
            
            self.stdout.write(self.style.SUCCESS('成功导入导航数据'))
            
        except FileNotFoundError:
            self.stdout.write(self.style.ERROR('未找到 nav_data.json 文件'))
        except json.JSONDecodeError:
            self.stdout.write(self.style.ERROR('nav_data.json 文件格式错误'))
        except Exception as e:
            self.stdout.write(self.style.ERROR(f'导入失败：{str(e)}'))